using System;
using System.Linq.Expressions;
using System.Web.Mvc;
using System.Web.Mvc.Html;

namespace ECommerce.Web.HtmlHelpers
{
    public static class HtmlHelperExtensions
    {
        public static MvcHtmlString ViewFor(this HtmlHelper htmlHelper, string view)
        {
            return htmlHelper.Hidden("view", view);
        }

        public static string IdFor<T, TProperty>(this HtmlHelper htmlHelper, Expression<Func<T, TProperty>> propertySelector)
        {
            return HtmlElementIdentityHelper.IdFor(propertySelector);
        }

        public static string NameFor<T, TProperty>(this HtmlHelper htmlHelper, Expression<Func<T, TProperty>> propertySelector)
        {
            return HtmlElementIdentityHelper.NameFor(propertySelector);
        }

        public static MvcHtmlString OutputFor<T, TProperty>(this HtmlHelper<T> htmlHelper, Expression<Func<T, TProperty>> propertySelector)
        {
            return OutputFor(htmlHelper, propertySelector, String.Empty);
        }

        public static MvcHtmlString OutputFor<T, TProperty>(this HtmlHelper<T> htmlHelper, Expression<Func<T, TProperty>> propertySelector, string format)
        {
            string id = HtmlElementIdentityHelper.IdFor(propertySelector);

            string value = GetPropertyValue(htmlHelper, propertySelector, format);

            string output = String.Format("<span id=\"{0}\">{1}</span>", id, htmlHelper.Encode(value));

            return MvcHtmlString.Create(output);
        }

        private static string GetPropertyValue<T, TProperty>(HtmlHelper<T> htmlHelper, Expression<Func<T, TProperty>> propertySelector, string format)
        {            
            TProperty value = propertySelector.Compile().Invoke(htmlHelper.ViewData.Model);

            if (String.IsNullOrEmpty(format))
            {
                return value.ToString();
            }

            return String.Format(format, value);
        }
    }
}